package SchemaVo::AggregateVo;

use strict;
use warnings;
use utf8;

use lib './src';

use SchemaVo::ModelVo;

# 从属性参数构造
sub New {
    my ($class, %param) = @_;

    my $self = {
        # 聚合 Id
        AggregateId => undef,
        # 组织名称
        CompanyName => undef,
        # 项目名称
        ProjectName => undef,
        # 聚合名称
        Name => undef,
        # 聚合父级包名
        AggregatePackage => undef,
        # 聚合定义
        Content => undef,
        # 聚合说明
        Comment => 'Empty Now',
        # 项目配置
        Config => undef,
        # 模型列表
        ModelVos => undef,
    };

    foreach my $key (keys %param){
        $self->{$key} = $param{$key};
    }

    bless $self, $class;

    return $self;
}

# 从聚合实体创建聚合值对象
sub FromAggregate {
    my ($class, $aggregate, $companyName, $projectName, $aggregatePackage) = @_;

    my @modelVos = map { SchemaVo::ModelVo->FromModel($_) } $aggregate->Models->all;

    my $self = {
        # 聚合 Id
        AggregateId => $aggregate->Id,
        # 组织名称
        CompanyName => $companyName,
        # 项目名称
        ProjectName => $projectName,
        # 聚合名称
        Name => $aggregate->Name,
        # 聚合父级包名
        AggregatePackage => $aggregatePackage,
        # 聚合定义
        Content => $aggregate->Content,
        # 聚合说明
        Comment => $aggregate->Comment,
        # 项目配置
        Config => undef,
        # 模型列表
        ModelVos => \@modelVos,
    };

    bless $self, $class;

    return $self;
}

# 生成定义代码
sub GenerateDefineCode {
    my ($self, $engine, $template) = @_;
    $engine->process($template, $self, \$self->{Content})
       || die $engine->error(), "\n";
    return $self->{Content};
}

# 使用字符串模板生成代码
sub GenerateCode {
    my ($self, $engine, $templateStr) = @_;
    my $result = '';
    $engine->process(\$templateStr, $self, \$result)
        || die $engine->error(), "\n";
    return $result;
}

# 返回普通的 Hash 表
sub ToPlainHash {
    my ($self) = @_;

    return {
        # 聚合 Id
        AggregateId => $self->{AggregateId},
        # 组织名称
        CompanyName => $self->{CompanyName},
        # 项目名称
        ProjectName => $self->{ProjectName},
        # 聚合名称
        Name => $self->{Name},
        # 聚合父级包名
        AggregatePackage => $self->{AggregatePackage},
        # 聚合定义
        Content => $self->{Content},
        # 聚合说明
        Comment => $self->{Comment},
        # 项目配置
        Config => $self->{Config},
        # 模型列表
        ModelVos => [
            map { $_->ToPlainHash } @{ $self->{ModelVos} }
        ],
    }
}

1;
